import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';
import { v4 as uuidv4 } from 'uuid';

@Injectable()
export class UploadService {
  private uploadPath = path.join(__dirname, '..', '..', '..', 'uploads');

  constructor() {
    // 确保上传目录存在
    if (!fs.existsSync(this.uploadPath)) {
      fs.mkdirSync(this.uploadPath, { recursive: true });
    }
  }

  async uploadFile(file: any): Promise<{ url: string }> {
    try {
      // 验证文件类型
      const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
      if (!allowedTypes.includes(file.mimetype)) {
        throw new HttpException('只允许上传图片文件', HttpStatus.BAD_REQUEST);
      }

      // 验证文件大小（限制为5MB）
      const maxSize = 5 * 1024 * 1024;
      if (file.size > maxSize) {
        throw new HttpException('文件大小不能超过5MB', HttpStatus.BAD_REQUEST);
      }

      // 生成唯一文件名
      const extension = path.extname(file.originalname);
      const filename = `${uuidv4()}${extension}`;
      const filepath = path.join(this.uploadPath, filename);

      // 保存文件
      fs.writeFileSync(filepath, file.buffer);

      // 返回可访问的URL路径
      return { url: `/uploads/${filename}` };
    } catch (error) {
      if (error instanceof HttpException) {
        throw error;
      }
      throw new HttpException('文件上传失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async deleteFile(filename: string): Promise<void> {
    try {
      const filepath = path.join(this.uploadPath, filename);
      if (fs.existsSync(filepath)) {
        fs.unlinkSync(filepath);
      }
    } catch (error) {
      throw new HttpException('文件删除失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}